package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjec.market.entity.InfoMarketMessage;
import com.fjec.market.mapper.InfoMarketMessageMapper;
import com.fjec.market.service.IInfoMarketMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import org.apache.commons.collections.MapUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 051.市场消息表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-10-22
 */
@Service
public class InfoMarketMessageServiceImpl extends ServiceImpl<InfoMarketMessageMapper, InfoMarketMessage> implements IInfoMarketMessageService {

    public static final String TITLE_KEY = "title";

    public static final String CONTENT_KEY = "content";

    @Resource
    private InfoMarketMessageMapper mapper;

    @Cacheable(value = "systemSetting", key = "'fjec:market:system_message' + #code")
    @Override
    public Map<String, Object> getMessageByCode(Integer code) {
        return doGetMessageByCode(code);
    }

    @CachePut(value = "systemSetting", key = "'fjec:market:system_message' + #code")
    @Override
    public Map<String, Object> cacheMessageByCode(Integer code) {
        return doGetMessageByCode(code);
    }

    @Override
    public Map<String, Object> formatMessageByCode(Integer code, Object... args) {
        Map<String, Object> map = this.getMessageByCode(code);
        if (map != null) {
            String content = MapUtils.getString(map, CONTENT_KEY);
            map.replace(CONTENT_KEY, Strings.lenientFormat(content, args));
        }
        return map;
    }

    private Map<String, Object> doGetMessageByCode(Integer code) {
        QueryWrapper<InfoMarketMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Code", code);
        InfoMarketMessage entity = mapper.selectOne(queryWrapper);
        Map<String, Object> resultMap = new HashMap<>();
        if (entity != null) {
            resultMap.put(TITLE_KEY, entity.getMsgTitle());
            resultMap.put(CONTENT_KEY, entity.getMsgContent());
        }
        return resultMap;
    }
}
